import pymysql
import urllib.request
import json
'''
自动更新全部基金的基本信息，包括涨幅、最小买入费率、基金经理等
'''

db = pymysql.connect("114.115.160.16", "root", "123456Aa!", "fund")
cursor = db.cursor()

headers = {
    "token": "atTPd9c8sA"
}

sql = "select fund_id from api_fund"

cursor.execute(sql)

for fund_id in cursor.fetchall():
    fund_id = fund_id[0]
    req = urllib.request.Request(
        url="https://api.doctorxiong.club/v1/fund/detail?code=" + fund_id + "&startDate=2021-05-14", headers=headers)
    response = urllib.request.urlopen(req).read().decode("UTF-8")
    try:
        fund_info = json.loads(response)["data"]

        buy_min = fund_info["buyMin"]
        manager = fund_info["manager"]
        buy_source_rate = fund_info["buySourceRate"]
        buy_rate = fund_info["buyRate"]
        day_growth = "0"
        if "dayGrowth" in fund_info.keys():
            day_growth = fund_info["dayGrowth"]
        week_growth = "0"
        if "lastWeekGrowth" in fund_info.keys():
            week_growth = fund_info["lastWeekGrowth"]
        month_growth = fund_info["lastMonthGrowth"]
        three_month_growth = fund_info["lastThreeMonthsGrowth"]
        six_month_growth = fund_info["lastSixMonthsGrowth"]
        year_growth = fund_info["lastYearGrowth"]

        net_worth = "0"
        if "netWorth" in fund_info.keys():
            net_worth = fund_info["netWorth"]
        print(net_worth)

        sql = '''update api_fund set buy_min=%f,manager='%s',buy_source_rate=%f,buy_rate=%f,day_growth=%f,
                week_growth=%f,month_growth=%f,three_month_growth=%f,six_month_growth=%f,year_growth=%f,price=%f 
                where fund_id='%s'
            ''' % (float(buy_min), manager, float(buy_source_rate),
            float(buy_rate), float(day_growth), float(week_growth), float(month_growth), float(three_month_growth),
            float(six_month_growth), float(year_growth), float(net_worth), fund_id
            )
        cursor.execute(sql)
        print("ok!",fund_id)
    except Exception as e:
        print(e)
db.commit()